package com.cskaoyan.service.front.goods;

import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.vo.back.BaseRespVo;
import com.cskaoyan.bean.vo.front.goodsvo.*;
import com.cskaoyan.exception.MarketValidationException;
import com.cskaoyan.mapper.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @program: SSMItem
 * @description
 * @author: YY
 * @create: 2022-10-13 23:16
 **/


@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCategoryMapper categoryMapper;

    @Autowired
    MarketAdMapper adMapper;

    @Autowired
    MarketBrandMapper brandMapper;
    @Autowired
    MarketTopicMapper topicMapper;
    @Autowired
    MarketSystemMapper systemMapper;

    @Autowired
    MarketSearchHistoryMapper searchHistoryMapper;

    @Autowired
    MarketKeywordMapper keywordMapper;


    @Override
    public GoodsIndexVo selectTables() {


        GoodsIndexVo goodsIndexVo = new GoodsIndexVo();


        Integer value = systemMapper.selectValueById(2);
        //新品
        List<NewGoodsListVo> newGoodsListVos = goodsMapper.selectNewGoods(true, false, value);


        //优惠卷
        List<CouponListVo> couponListVos = couponMapper.selectCoupon(false);


        List<Channel> channels = categoryMapper.selectCategory(false);

        //轮播图
        List<Banner> banners = adMapper.selectBanner(false, true);


        Integer value1 = systemMapper.selectValueById(17);
        //制造商
        List<BrandList> brandLists = brandMapper.selectBrand(false, value1);


        Integer value2 = systemMapper.selectValueById(10);
        //人气
        List<HotGoodsList> hotGoodsLists = goodsMapper.selectHotGoods(true, false, value2);


        Integer value3 = systemMapper.selectValueById(18);
        //专题
        List<TopicList> topicLists = topicMapper.selectTopic(false, value3);


        Integer value4 = systemMapper.selectValueById(15);
        List<FloorGoodsList> floorGoodsLists = categoryMapper.selectFloorGoods(false, value4);


        for (FloorGoodsList floorGoodsList : floorGoodsLists) {

            if (floorGoodsList != null) {
                Integer value5 = systemMapper.selectValueById(12);
                List<NewGoodsListVo> newGoodsListVo = goodsMapper.selectFloorGoodsByCategoryId(floorGoodsList.getId(), false, value5);
                floorGoodsList.setGoodsList(newGoodsListVo);

            }
        }

        goodsIndexVo.setNewGoodsList(newGoodsListVos);
        goodsIndexVo.setCouponList(couponListVos);
        goodsIndexVo.setChannel(channels);
        goodsIndexVo.setBanner(banners);
        goodsIndexVo.setBrandList(brandLists);
        goodsIndexVo.setHotGoodsList(hotGoodsLists);
        goodsIndexVo.setTopicList(topicLists);
        goodsIndexVo.setFloorGoodsList(floorGoodsLists);

        return goodsIndexVo;
    }

    @Override
    public Integer selectGoodsCount() {
        int count = goodsMapper.selectGoodsCount();
        return count;
    }

    @Override
    public CategoryVo selectGoodsByCategory(Integer id) {
        //id 是点击类目得类目id

        CategoryVo categoryVo = new CategoryVo();
        //我们要获得当前类目、父类目以及父类目下的所有类目

        //子类目：子类目得pid = id;
        //父类目：类目id不变
        //当前类目：也是id = id

        Integer integers = categoryMapper.selectPidById(id);
        if (integers == 0) {
            //首先获取父类目
            MarketCategory marketCategory = categoryMapper.selectParentCategory(id);
            //获得子类目得集合

            List<MarketCategory> marketCategoryList = categoryMapper.selectCategoryListById(id);
            for (MarketCategory category : marketCategoryList) {
                if (true) {
                    categoryVo.setCurrentCategory(category);
                    break;
                }
            }

            categoryVo.setParentCategory(marketCategory);

            categoryVo.setBrotherCategory(marketCategoryList);

            return categoryVo;
        }

        Integer pid = categoryMapper.selectPid(id);

        MarketCategory marketCategory = categoryMapper.selectParentCategory(pid);
        List<MarketCategory> marketCategoryList = categoryMapper.selectCategoryListById(pid);


        for (MarketCategory category : marketCategoryList) {
            if (Objects.equals(id, category.getId())) {
                categoryVo.setCurrentCategory(category);
            }
        }
        categoryVo.setParentCategory(marketCategory);

        categoryVo.setBrotherCategory(marketCategoryList);


        return categoryVo;

    }

    //通过categoryId获得该类目下的所有商品
    @Override
    public GoodsListCategoryVo selectGoodsListVoCategory(Integer categoryId, Integer limit, Integer page) {

        GoodsListCategoryVo goods = new GoodsListCategoryVo();
        List<HotGoodsList> hotGoodsLists = goodsMapper.selectHotGoodsListByCategoryId(categoryId, ((page - 1) * limit));


        List<FilterCategoryVo> filterCategoryVos = categoryMapper.selectFilterCategoryById("L2");

        int total = goodsMapper.selectGoodsCountByCategoryId(categoryId);
        int pages = 0;
        if (total < limit) {
            pages = 1;
        } else if (total % limit == 0) {
            pages = total / limit;
        } else {
            pages = total / limit + 1;
        }

        goods.setList(hotGoodsLists);
        goods.setTotal(total);
        goods.setPages(pages);
        goods.setFilterCategoryList(filterCategoryVos);
        return goods;

    }

    @Override
    public GoodsListBrandVo selectGoodsListVoBrand(Integer brandId, Integer page, Integer limit) {
        GoodsListBrandVo goods = new GoodsListBrandVo();
        List<HotGoodsList> hotGoodsLists = goodsMapper.selectGoodsByBrandId(brandId, (page - 1) * limit);
        List<FilterCategoryVo> filterCategoryVos = categoryMapper.selectFilterCategoryById("L2");
        int total = goodsMapper.selectGoodsCountByBrandId(brandId);
        int pages = 0;
        if (total < limit) {
            pages = 1;
        } else if (total % limit == 0) {
            pages = total / limit;
        } else {
            pages = total / limit + 1;
        }

        goods.setList(hotGoodsLists);
        goods.setTotal(total);
        goods.setPages(pages);
        goods.setFilterCategoryList(filterCategoryVos);
        return goods;

    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @SneakyThrows
    @Override
    public GoodsListBrandVo selectGoodsByKeywords(String keyword, BaseParam baseParam, HttpServletRequest request) {


        String agent = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgent.parseUserAgentString(agent);
        //来源
        String from = userAgent.toString();

        //获取userId
        Integer userId = null;
        //实现向历史搜索表中插入数据

        //MarketUser user = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        try {
            MarketUser user = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            userId = user.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //首先判断该关键词是否已经存在
        int rows = searchHistoryMapper.selectKeyword(keyword);

        //不存在并且登录状态
        if (rows == 0 && userId != null) {
            MarketSearchHistory SearchHistory = new MarketSearchHistory();
            SearchHistory.setKeyword(keyword);
            SearchHistory.setUserId(userId);
            SearchHistory.setFrom(from);
            SearchHistory.setAddTime(new Date());
            SearchHistory.setUpdateTime(new Date());
            SearchHistory.setDeleted(false);
            searchHistoryMapper.insert(SearchHistory);
        } else {
            //存在且登录状态
            Date date = new Date();
            searchHistoryMapper.updateTime(date, userId, keyword);
        }


        //查询对应的SortOrder
        Integer SortOrder = keywordMapper.selectSortOrderByKeyword(keyword);

        if (SortOrder != null) {
            keywordMapper.updateSortOrder(SortOrder + 1, keyword);
        }

        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        List<HotGoodsList> hotGoodsLists = goodsMapper.selectGoodsByKeyword("%" + keyword + "%");
        ArrayList<FilterCategoryVo> filterCategoryVos = new ArrayList<>();
        PageInfo<HotGoodsList> hotGoodsListPageInfo = new PageInfo<>(hotGoodsLists);


        Integer id = hotGoodsLists.get(0).getId();
        Integer CategoryId = goodsMapper.selectCategoryIdById(id);
        Integer pid = categoryMapper.selectPidById(CategoryId);
        FilterCategoryVo f = categoryMapper.selectCategoryByGoodsId(pid);
        filterCategoryVos.add(f);

//        for (HotGoodsList hotGoodsList : hotGoodsLists) {
//            if (hotGoodsList != null) {
//                ///拿到goods表中的id 对应Category的id
//                Integer CategoryId = goodsMapper.selectCategoryIdById(hotGoodsList.getId());
//                //通过Category的id查询pid
//                Integer pid = categoryMapper.selectPidById(CategoryId);
//                FilterCategoryVo f = categoryMapper.selectCategoryByGoodsId(pid);
//                if (f != null) {
//                    filterCategoryVos.add(f);
//                }
//            }
//        }


        GoodsListBrandVo data = GoodsListBrandVo.data(hotGoodsListPageInfo, filterCategoryVos);
        return data;
    }


    //  ----------------------------------

    @Autowired
    MarketGoodsSpecificationMapper specificationMapper;
    @Autowired
    MarketIssueMapper issueMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketGoodsAttributeMapper attributeMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketFootprintMapper footprintMapper;


    @Override
    public GoodsDetailVo detail(Integer id, Integer userId) {

        // 新建返回对象
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();


        // info
        MarketGoods marketGoods = goodsMapper.selectByPrimaryKey(id);
        goodsDetailVo.setInfo(marketGoods);

        //历史足迹
        MarketFootprint marketFootprint = new MarketFootprint();
        if (userId != 0) {
            marketFootprint.setDeleted(false);
            marketFootprint.setGoodsId(id);
            marketFootprint.setUserId(userId);
            marketFootprint.setAddTime(new Date());
            marketFootprint.setUpdateTime(new Date());
            footprintMapper.insert(marketFootprint);
        }

        // 1.根据商品id查询商品的规格
        MarketGoodsSpecificationExample example = new MarketGoodsSpecificationExample();
        example.createCriteria().andGoodsIdEqualTo(id);
        example.createCriteria().andDeletedEqualTo(false);
        List<MarketGoodsSpecification> specificationLists = specificationMapper.selectByExample(example);

        // 分装进返回对象的specificationList成员变量
        List<SpecificationListVo> specificationListVo = new ArrayList<>();
        SpecificationListVo specificationList = new SpecificationListVo();
        String name = specificationLists.get(0).getSpecification();
        specificationList.setName(name);
        specificationList.setValueList(specificationLists);
        specificationListVo.add(specificationList);
        goodsDetailVo.setSpecificationList(specificationListVo);

        // 2.groupon
        List<MarketGroupon> groupon = new ArrayList<>();
        goodsDetailVo.setGroupon(groupon);

        // 3.issue
        MarketIssueExample example1 = new MarketIssueExample();
        List<MarketIssue> marketIssues = issueMapper.selectByExample(example1);
        goodsDetailVo.setIssue(marketIssues);

        // 4.userHasCollect
        // 查询当前用户id是否以及商品id是否存在收藏表，存在则赋值为1，不存在则为0
        MarketCollectExample example5 = new MarketCollectExample();
        MarketCollectExample.Criteria criteria = example5.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andValueIdEqualTo(id);
        List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(example5);
        if (marketCollects != null) {
            goodsDetailVo.setUserHasCollect(1);
        }
        goodsDetailVo.setUserHasCollect(0);

        // 5.comment  通过商品id查询评论
        PageHelper.startPage(1, 2);
        GoodsDetailCommentVo goodsDetailCommentVo = new GoodsDetailCommentVo();
        MarketCommentExample example2 = new MarketCommentExample();
        example2.createCriteria().andValueIdEqualTo(id);
        List<MarketComment> marketComments = commentMapper.selectByExample(example2);
        Integer count = commentMapper.selectCount(id);
        goodsDetailCommentVo.setCount(count);


        goodsDetailCommentVo.setData(marketComments);
        goodsDetailVo.setComment(goodsDetailCommentVo);


        // 6. share
        boolean b = systemMapper.selectMarketWxShare("market_wx_share");
        goodsDetailVo.setShare(b);

        // 7.attribute根据商品id
        MarketGoodsAttributeExample example3 = new MarketGoodsAttributeExample();
        example3.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsAttribute> marketGoodsAttributes = attributeMapper.selectByExample(example3);
        goodsDetailVo.setAttribute(marketGoodsAttributes);

        // 8.brand 根据商品表中的brandId查询brand
        MarketBrand marketBrand = brandMapper.selectByPrimaryKey(marketGoods.getBrandId());
        goodsDetailVo.setBrand(marketBrand);

        // 9.productList
        MarketGoodsProductExample example4 = new MarketGoodsProductExample();
        example4.createCriteria().andGoodsIdEqualTo(id);
        List<MarketGoodsProduct> marketGoodsProducts = goodsProductMapper.selectByExample(example4);
        goodsDetailVo.setProductList(marketGoodsProducts);


        return goodsDetailVo;
    }


    @Override
    public GoodsRelatedVo selectRelatedGoods(Integer id) {
        //通过userId 查询到类目id 从而获取同类目下的商品

        GoodsRelatedVo goodsRelatedVo = new GoodsRelatedVo();

        goodsRelatedVo.setPage(1);
        goodsRelatedVo.setLimit(6);
        goodsRelatedVo.setPages(1);
        goodsRelatedVo.setTotal(6);
        //1.查询category_id
        Integer categoryId = goodsMapper.selectCategoryIdById(id);
        //通过categoryId查询到该类目下的所有商品

        List<HotGoodsList> goodsList = goodsMapper.selectGoodsByCategoryId(categoryId);

        goodsRelatedVo.setList(goodsList);

        return goodsRelatedVo;
    }

    @Override
    public GoodsListBrandVo1 selectGoodsOrderByRetailPrice(BaseParam baseParam, String keyword, Integer categoryId) {
        GoodsListBrandVo1 goodsListBrandVo = new GoodsListBrandVo1();


        if (baseParam.getSort().equals("retail_price")) {

            //分页
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
            MarketGoodsExample example = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andKeywordsLike("%" + keyword + "%");
            example.setDistinct(true);
            example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());

            List<MarketGoods> goods = goodsMapper.selectByExample(example);
            ArrayList<HotGoodsList1> hotGoodsLists = new ArrayList<>();

            for (MarketGoods good : goods) {
                HotGoodsList1 hotGood = new HotGoodsList1(
                        good.getId(),
                        good.getName(),
                        good.getBrief(),
                        good.getPicUrl(),
                        good.getIsNew(),
                        good.getIsHot(),
                        good.getCounterPrice(),
                        good.getRetailPrice()
                );
                hotGoodsLists.add(hotGood);
            }

            List<FilterCategoryVo> filterCategoryVos = categoryMapper.selectFilterCategoryById1(categoryId);


            goodsListBrandVo.setList(hotGoodsLists);
            goodsListBrandVo.setFilterCategoryList(filterCategoryVos);
            goodsListBrandVo.setPage(baseParam.getPage());
            criteria.andKeywordsLike(keyword);
            goodsListBrandVo.setTotal(goods.size());
            if (goods.size() < baseParam.getLimit()) {
                goodsListBrandVo.setPages(baseParam.getPage());
            }
            if (goods.size() % baseParam.getLimit() == 0) {
                goodsListBrandVo.setPages(goods.size() % baseParam.getLimit());
            } else {
                goodsListBrandVo.setPages(goods.size() % baseParam.getLimit() + 1);
            }
            goodsListBrandVo.setLimit(baseParam.getLimit());
            return goodsListBrandVo;
        } else {

            //分页
            PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());
            MarketGoodsExample example = new MarketGoodsExample();
            MarketGoodsExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false);
            criteria.andCategoryIdEqualTo(categoryId);
            example.setDistinct(true);
            example.setOrderByClause(baseParam.getSort() + " " + baseParam.getOrder());

            List<MarketGoods> goods = goodsMapper.selectByExample(example);
            ArrayList<HotGoodsList1> hotGoodsLists = new ArrayList<>();

            for (MarketGoods good : goods) {
                HotGoodsList1 hotGood = new HotGoodsList1(
                        good.getId(),
                        good.getName(),
                        good.getBrief(),
                        good.getPicUrl(),
                        good.getIsNew(),
                        good.getIsHot(),
                        good.getCounterPrice(),
                        good.getRetailPrice()
                );
                hotGoodsLists.add(hotGood);
            }

            List<FilterCategoryVo> filterCategoryVos = categoryMapper.selectFilterCategoryById2(categoryId);


            goodsListBrandVo.setList(hotGoodsLists);
            goodsListBrandVo.setFilterCategoryList(filterCategoryVos);
            goodsListBrandVo.setPage(baseParam.getPage());
            goodsListBrandVo.setTotal(goods.size());
            if (goods.size() < baseParam.getLimit()) {
                goodsListBrandVo.setPages(baseParam.getPage());
            }
            if (goods.size() % baseParam.getLimit() == 0) {
                goodsListBrandVo.setPages(goods.size() % baseParam.getLimit());
            } else {
                goodsListBrandVo.setPages(goods.size() % baseParam.getLimit() + 1);
            }
            goodsListBrandVo.setLimit(baseParam.getLimit());
            return goodsListBrandVo;
        }


    }
}
